﻿using BSWDEEPLEARNWrapper;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Station.Inspect.SuaModel
{
	class ModelBswSeg:ModelBase
    {
		private bswSegEvaluator model;

		void ClearModel()
		{
			if(model !=null)
            {
				model.SegRelease();
				model = null;
            }
			minID = -1;
			maxID = -1;
		}

		public bool LoadModel(string fileName)
		{
			ClearModel();
			if (TryParseName(fileName) == false)
				return false;
			model = new bswSegEvaluator(fileName, 0, false, false);
			if(model.status != SegStatus.Seg_Success)
            {
				return false;
            }
			bool isWarmup = model.Warmup(5);
			if (!isWarmup)
			{
				//Log.Instance.Error($"节点[{Name}]分割模型显卡热身失败");
				return false;
			}
			return true;
		}

		public bool Run(Bitmap img,double threshold, out List<SegResult> res)
        {
			res = new List<SegResult>();
			var curRes = new List<SegResult>();
			bool result = false;
			if (model != null)
            {
				var bi = GetImagePixel(img);
				CutImgParam cutParam = new CutImgParam();
				cutParam.is_save_cut = false;//isSaveCut && string.IsNullOrEmpty(imageName) == false;
				cutParam.cut_image_path = "D:\\Bsw_work\\AI_Pro\\AI_Pro\\BSW_DEEPLAERN_CS_Demo\\segment\\seg0001\\cut_image";
				cutParam.cut_image_prefix = "Test";//Path.GetFileNameWithoutExtension(paths[i]);
				cutParam.cut_image_width = 256;
				cutParam.cut_image_height = 256;
				//List<SegResult> resSegs = new List<SegResult>();
				result = model.SegmentEvaluate(bi.Result, bi.width, bi.height, bi.Channels, bi.Stride, cutParam, curRes);
			}
			if (model==null || result == false)
			{
				SegResult tmpSeg = new SegResult();
				tmpSeg.x = 1;
				tmpSeg.y = 1;
				tmpSeg.w = img.Width - 2;
				tmpSeg.h = img.Height - 2;
				tmpSeg.prob = 1;
				tmpSeg.name = model==null?"算子为空":"算子报错";
				tmpSeg.area = tmpSeg.w * tmpSeg.h;
				tmpSeg.rCenter = new Point((tmpSeg.x + tmpSeg.w) / 2, (tmpSeg.y + tmpSeg.h) / 2);
				tmpSeg.rSize = new Size(tmpSeg.w, tmpSeg.h);
				tmpSeg.points = new List<Point>();
				tmpSeg.points.Add(new Point(1,1));
				tmpSeg.points.Add(new Point(tmpSeg.x+ tmpSeg.w, 1));
				tmpSeg.points.Add(new Point(tmpSeg.x + tmpSeg.w, tmpSeg.y+tmpSeg.h));
				tmpSeg.points.Add(new Point(1, tmpSeg.y + tmpSeg.h));
				curRes.Add(tmpSeg);
			}
			res.AddRange(curRes.Where(p=>p.prob>threshold));
			return res.Count>0;
		}
	}
}
